package vn.com.bookstore.controller;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import vn.com.bookstore.domain.model.Account;
import vn.com.bookstore.model.vo.CustomerVO;
import vn.com.bookstore.model.vo.ErrorJson;
import vn.com.bookstore.service.CustomerService;
import vn.com.bookstore.utils.GenerateMD5;

@Controller
public class ManageCustomerController {
	private static final Logger logger = LoggerFactory.getLogger(ManageCustomerController.class);
	private static final String PHONE_PATTERN = "[0-9]+";
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	@Autowired
	private CustomerService customerService;
	
	
	@RequestMapping(value = "/online/view-profile", method = RequestMethod.GET)
	public String openCustomerProfile(Model model) {
		SecurityContext context = SecurityContextHolder.getContext();
		String username = context.getAuthentication().getName();
		CustomerVO customerVO = customerService
				.getCustomerVOByUsername(username);
		Account account = customerService.getAccountById(customerVO
				.getAccountId());
		model.addAttribute("account", account);
		model.addAttribute("customerVO", customerVO);
		return "website/account/customer-profile";
	}

	@RequestMapping(value = "/online/changeProfileCustomer", method = RequestMethod.POST)
	public @ResponseBody
	ErrorJson changeProfileCus(Model model,
			@ModelAttribute("customerVO") CustomerVO customerVO) {
		ErrorJson errorJson = new ErrorJson();
		errorJson.setValidate(true);
		Pattern phonePattern = Pattern.compile(PHONE_PATTERN);
		Pattern emailPattern = Pattern.compile(EMAIL_PATTERN);
		
		if (StringUtils.isEmpty(customerVO.getBirthday())) {
			errorJson.setErrorDOB("Cần nhập thông tin");
			errorJson.setValidate(false);
		} else if (!customerService.validateDate(customerVO.getBirthday())) {
			errorJson.setErrorDOB("Ngày sinh không đúng (dd/MM/yyyy)");
			errorJson.setValidate(false);
		}
		if (StringUtils.isEmpty(customerVO.getPhone())) {
			errorJson.setErrorPhone("Cần nhập thông tin");
			errorJson.setValidate(false);
		} else if (!phonePattern.matcher(customerVO.getPhone()).matches()) {
			errorJson.setErrorPhone("Số điện thoại không hợp lệ!");
			errorJson.setValidate(false);
		}
		if (StringUtils.isEmpty(customerVO.getEmail())) {
			errorJson.setErrorMail("Cần nhập thông tin");
			errorJson.setValidate(false);
		} else if (!emailPattern.matcher(customerVO.getEmail()).matches()) {
			errorJson.setErrorMail("Email không hợp lệ (VD: abc@example.com)!");
			errorJson.setValidate(false);
		}
		if(!errorJson.isValidate()){
			return errorJson;
		}
		customerService.updateCustomerProfile(customerVO);
		return errorJson;
	}
	
	@RequestMapping(value="/online/changePasswordCustomer", method=RequestMethod.POST)
	public @ResponseBody ErrorJson changePassword(Model model,
			@RequestParam("oldpass") String oldPass,
			@RequestParam("newpass") String newPass,
			@RequestParam("reNewpass") String reNewPass,
			@RequestParam("id") int id ){
		ErrorJson errorJson = new ErrorJson();
		errorJson.setValidate(true);
		if(StringUtils.isEmpty(oldPass)){
			errorJson.setErrorPass("Cần nhập thông tin!");
			errorJson.setValidate(true);
		} else if (!customerService.checkOldPassword(oldPass, id)) {
			errorJson.setErrorPass("Mật khẩu cũ không đúng!");
			errorJson.setValidate(false);
			return errorJson;
		} 
		
		if(StringUtils.isEmpty(newPass) || newPass.length() < 8){
			errorJson.setErrorPass("Cần nhập thông tin mật khẩu mới (Tối thiểu 8 ký tự)!");
			errorJson.setValidate(false);
		} 
		
		if(!newPass.equals(reNewPass)) {
			errorJson.setErrorPass("Mật khẩu nhập lại chưa đúng!");
			errorJson.setValidate(false);
		}
		if(!errorJson.isValidate()){
			return errorJson;
		}
		try {
			Account account = customerService.getAccountById(id);
			account.setPassword(GenerateMD5.MD5(newPass));
			customerService.updateAccountCustomer(account);
		} catch (Exception e) {
			logger.info("changePassword" + e.getMessage());
		}
		return errorJson;
	}
}
